/*
 * @Author: jingfuu@163.com
 * @Date: 2024-09-14 17:02:45
 * @LastEditTime: 2024-10-06 22:05:06
 * @Description: 自定义的异常过滤器，拦截异常，返回统一的对象
 */
import { ExceptionFilter, Catch, ArgumentsHost, Logger } from '@nestjs/common';
import { Response } from 'express';
import { R } from '../R';

@Catch() // 不传入任何参数，表示捕获所有异常
export class DefaultExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(DefaultExceptionsFilter.name);

  catch(exception: Error, host: ArgumentsHost) {
    this.logger.error(exception.stack);
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = 200; // 默认状态码为 500（服务器内部错误）
    const message = exception.message || 'Internal server error'; // 默认错误消息
    // 发送响应
    response
      .status(status)
      .json(R.fail(message, (exception as any).status || 500));
  }
}
